package com.sc.nft.consume;

import cn.hutool.core.util.StrUtil;
import com.sc.nft.entity.UserEcologyHatchRecords;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.service.EcologySmeltingService;
import com.sc.nft.util.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.Redisson;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@RocketMQMessageListener(topic = MessageTopic.ECOLOGY_HATCH_SETTLE_PERFORMANCE_TOPIC + "${spring.profiles.active}", consumerGroup = MessageTopic.ECOLOGY_HATCH_SETTLE_PERFORMANCE_TOPIC + "${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class EcologyHatchSettlePerformanceConsumer implements RocketMQListener<UserEcologyHatchRecords> {

    private final Redisson redisson;
    private final RedisTemplate redisTemplate;
    private final EcologySmeltingService ecologySmeltingService;

    /**
     * 熔炼之后  业绩处理
     * 1.确认当前用户是不是DAO的主理人团队里
     *
     * @param userEcologyHatchRecords
     */
    @Override
    public void onMessage(UserEcologyHatchRecords userEcologyHatchRecords) {
        log.info("熔炼 业绩处理：{}", userEcologyHatchRecords.getId());
        try {
            Thread.sleep(5000);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String key = RedisKeyEnum.ECOLOGY_HATCH_SETTLE_PERFORMANCE_TOPIC_LOCK.getKey() + userEcologyHatchRecords.getId();
        Long increment = redisTemplate.opsForValue().increment(key);
        redisTemplate.expire(key, 180, TimeUnit.MINUTES);
        if (increment.longValue() > 1L) {
            return;
        }

        try {
            ecologySmeltingService.settlePerformance(userEcologyHatchRecords);
        } catch (Exception e) {
            WeChatUtil.sendWeChatMessage(StrUtil.format("熔炼-业绩处理 记录id：{},异常:{}", userEcologyHatchRecords.getId(), e));
            log.error("熔炼-业绩处理 记录id：{} 异常:{}", userEcologyHatchRecords.getId(), e);
        }

    }
}
